<template>
	<div class="page_user" id="user_participation">
		<div class="warp">
			<div class="container">
				<div class="row">
					<div class="col-12 col-md-3">
						<div class="card_menu">
							<!-- 左侧边栏 -->
							<list_menu_user :list_info="list_info"></list_menu_user>
						</div>
					</div>

					<div class="col-12 col-md-9">
						<div class="card_info pl-2">
							<div class="participation_header">
								<h3>{{ t('myRegistrationsTitle') }}</h3>
								<p class="subtitle">{{ t('viewAllRegistrations') }}</p>
							</div>

							<!-- 报名列表 -->
							<div class="participation_list" v-if="list.length > 0">
								<div class="participation_item" v-for="(item, index) in list" :key="item.user_participation_id || index">
									<div class="participation_card">
										<div class="card_header">
											<h4 class="conference_name">{{ $getBilingualText(item.conference_name) || t('unnamedConference') }}</h4>
											<div class="status_badges">
												<span class="badge" 
													:class="getExamineStateClass(item.examine_state || item.examineState)">
													{{ getExamineStateText(item.examine_state || item.examineState) }}
												</span>
												<span class="badge" 
													:class="getPayStateClass(item.pay_state || item.payState)">
													{{ getPayStateText(item.pay_state || item.payState) }}
												</span>
											</div>
										</div>
										
										<div class="card_body">
											<div class="info_row">
												<span class="info_label">{{ t('meetingNumber') }}：</span>
												<span class="info_value">{{ item.meeting_number || '-' }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('meetingTime') }}：</span>
												<span class="info_value">{{ formatDateTime(item.meeting_time) || '-' }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('meetingVenue') }}：</span>
												<span class="info_value">{{ $getBilingualText(item.meeting_venue) || '-' }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('participationAmount') }}：</span>
												<span class="info_value amount">¥{{ item.amount_of_participation || 0 }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('userNameField') }}：</span>
												<span class="info_value">{{ getAttendeeNames(item) }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('accommodationStatus') }}：</span>
												<span class="info_value">{{ getAccommodationStatus(item) }}</span>
											</div>
											<div class="info_row" v-if="item.pay_type">
												<span class="info_label">{{ t('paymentMethod') }}：</span>
												<span class="info_value">{{ item.pay_type }}</span>
											</div>
											<div class="info_row">
												<span class="info_label">{{ t('registrationTime') }}：</span>
												<span class="info_value">{{ $toTime(item.create_time, 'yyyy-MM-dd hh:mm:ss') }}</span>
											</div>
										</div>
										
										<div class="card_footer">
											<button 
												v-if="!isPaid(item.pay_state) && item.user_participation_id"
												class="btn_pay"
												@click="goToPayment(item)">
												{{ t('goToPayment') }}
											</button>
											<button 
												class="btn_view"
												@click="viewDetails(item)">
												{{ t('viewDetails') }}
											</button>
										</div>
									</div>
								</div>
							</div>

							<!-- 空状态 -->
							<div class="empty_state" v-else>
								<div class="empty_icon">📋</div>
								<p class="empty_text">{{ t('noRegistrations') }}</p>
								<router-link to="/meeting_information/list" class="btn_primary">
									{{ t('registerNow') }}
								</router-link>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import mixin from "@/mixins/page.js";
import mixinI18n from "@/mixins/i18n.js";
import list_menu_user from "@/components/diy/list_menu_user.vue";

export default {
	mixins: [mixin, mixinI18n],
	components: {
		list_menu_user,
	},
	data() {
		return {
			url_get_list: "~/api/user_participation/get_list?",
			list: [],
		};
	},
	computed: {
		list_info() {
			return [
				{
					title: this.t('personalInfo'),
					url: "/user/info",
					icon: "house-fill",
					selected: false,
				},
				{
					title: this.t('changePassword'),
					url: "/user/password",
					icon: "person-fill",
					selected: false,
				},
				{
					title: this.t('myRegistrations'),
					url: "/user/participation",
					icon: "file-earmark-text-fill",
					selected: true,
				},
				{
					title: this.t('favorites'),
					url: "/user/collect",
					icon: "heart-fill",
					selected: false,
				},
			];
		},
	},
	methods: {
		async get_list() {
			// 先检查并获取用户信息
			const user = this.$store.state.user;
			let user_id = user && user.user_id;
			
			// 如果 store 中没有用户信息，尝试从 token 获取
			if (!user_id || user_id === 0) {
				const token = $.db.get("token");
				if (token) {
					// 尝试获取用户信息
					try {
						await this.$get_user((user) => {
							user_id = user.user_id;
						});
					} catch (e) {
						console.warn('获取用户信息失败:', e);
					}
				}
			}
			
			// 最终检查
			if (!user_id || user_id === 0) {
				this.$message.warning('请先登录');
				this.$router.push('/account/login');
				return;
			}

			try {
				const json = await this.$get(this.url_get_list, {
					participants: user_id,
					size: 100 // 获取所有记录
				});

				if (json.result && json.result.list) {
					this.list = json.result.list;
				} else if (json.result && Array.isArray(json.result)) {
					this.list = json.result;
				} else {
					this.list = [];
				}
				
				// 调试：打印第一条记录的审核状态
				if (this.list && this.list.length > 0) {
					console.log('=== 获取到的报名数据（前3条） ===');
					console.log('完整响应数据:', json);
					this.list.slice(0, 3).forEach((item, index) => {
						console.log(`记录${index + 1} - 所有字段名:`, Object.keys(item));
						console.log(`记录${index + 1}:`, {
							user_participation_id: item.user_participation_id,
							// 检查可能的字段名变体
							'examine_state': item.examine_state,
							'examineState': item.examineState,
							'examine_state_raw': JSON.stringify(item.examine_state || item.examineState),
							'examine_state_type': typeof (item.examine_state || item.examineState),
							'examine_state_length': (item.examine_state || item.examineState) ? String(item.examine_state || item.examineState).length : 0,
							'examine_state_trimmed': (item.examine_state || item.examineState) ? String(item.examine_state || item.examineState).trim() : null,
							pay_state: item.pay_state,
							// 完整的item对象（用于调试）
							full_item: item
						});
						// 测试状态判断方法 - 使用实际的字段值
						const actualExamineState = item.examine_state || item.examineState;
						console.log(`  实际使用的字段值: "${actualExamineState}"`);
						console.log(`  状态判断 - getExamineStateText: "${this.getExamineStateText(actualExamineState)}"`);
						console.log(`  状态判断 - getExamineStateClass: "${this.getExamineStateClass(actualExamineState)}"`);
					});
				}
			} catch (error) {
				console.error('获取报名列表失败:', error);
				this.$message.error('获取报名列表失败');
				this.list = [];
			}
		},
		// 获取审核状态的CSS类
		getExamineStateClass(examineState) {
			// 调试日志
			console.log('[getExamineStateClass] 输入值:', examineState, '类型:', typeof examineState);
			
			if (!examineState) {
				console.log('[getExamineStateClass] examineState为空，返回badge_info');
				return 'badge_info';
			}
			// 去除空格并统一比较（支持"已审核"、"已通过"、"已审核 "、" 已审核"等）
			const state = String(examineState).trim();
			console.log('[getExamineStateClass] 处理后状态:', state, '长度:', state.length);
			
			// 已审核/已通过/Examined/Passed 都视为已审核状态
			const isApproved = state === '已审核' || state === '已通过' || 
			    state === 'Examined' || state === 'Passed' ||
			    state.toLowerCase() === 'examined' || state.toLowerCase() === 'passed';
			
			console.log('[getExamineStateClass] 是否为已审核状态:', isApproved);
			
			if (isApproved) {
				return 'badge_success';
			}
			return 'badge_info';
		},
		// 获取审核状态的显示文本
		getExamineStateText(examineState) {
			// 调试日志
			console.log('[getExamineStateText] 输入值:', examineState, '类型:', typeof examineState);
			
			if (!examineState) {
				console.log('[getExamineStateText] examineState为空，返回未审核');
				return this.t('notExamined');
			}
			// 去除空格并统一比较
			const state = String(examineState).trim();
			console.log('[getExamineStateText] 处理后状态:', state, '长度:', state.length);
			
			// 已审核/已通过/Examined/Passed 都显示为"已审核"（或对应的翻译）
			const isApproved = state === '已审核' || state === '已通过' || 
			    state === 'Examined' || state === 'Passed' ||
			    state.toLowerCase() === 'examined' || state.toLowerCase() === 'passed';
			
			console.log('[getExamineStateText] 是否为已审核状态:', isApproved);
			
			if (isApproved) {
				const result = this.t('examined');
				console.log('[getExamineStateText] 返回已审核文本:', result);
				return result;
			}
			const result = this.t('notExamined');
			console.log('[getExamineStateText] 返回未审核文本:', result);
			return result;
		},
		// 获取支付状态的CSS类
		getPayStateClass(payState) {
			if (!payState) {
				return 'badge_warning';
			}
			const state = String(payState).trim();
			if (state === '已支付' || state === 'Paid' || state.toLowerCase() === 'paid') {
				return 'badge_success';
			}
			return 'badge_warning';
		},
		// 获取支付状态的显示文本
		getPayStateText(payState) {
			if (!payState) {
				return this.t('unpaid');
			}
			const state = String(payState).trim();
			if (state === '已支付' || state === 'Paid' || state.toLowerCase() === 'paid') {
				return this.t('paid');
			}
			return this.t('unpaid');
		},
		// 判断是否已支付
		isPaid(payState) {
			if (!payState) {
				return false;
			}
			const state = String(payState).trim();
			return state === '已支付' || state === 'Paid' || state.toLowerCase() === 'paid';
		},
		// 格式化日期时间
		formatDateTime(value) {
			if (!value) return '';
			// 如果是时间戳（数字）
			if (typeof value === 'number') {
				const date = new Date(value);
				if (isNaN(date.getTime())) {
					return value;
				}
				return this.formatDate(date);
			}
			// 如果是字符串，尝试解析
			if (typeof value === 'string') {
				// 如果是时间戳字符串
				if (/^\d{10,13}$/.test(value)) {
					const timestamp = value.length === 10 ? parseInt(value) * 1000 : parseInt(value);
					const date = new Date(timestamp);
					if (!isNaN(date.getTime())) {
						return this.formatDate(date);
					}
				}
				// 尝试解析日期字符串
				const date = new Date(value);
				if (!isNaN(date.getTime())) {
					return this.formatDate(date);
				}
				return value;
			}
			// 如果是Date对象
			if (value instanceof Date) {
				return this.formatDate(value);
			}
			return String(value);
		},
		// 格式化日期为可读字符串
		formatDate(date) {
			if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
				return '';
			}
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		// 获取参会人姓名（从attendees数组中提取）
		getAttendeeNames(item) {
			if (!item.attendees || !Array.isArray(item.attendees) || item.attendees.length === 0) {
				return '-';
			}
			// 提取所有参会人的姓名，用逗号分隔
			return item.attendees.map(a => a.name || '').filter(n => n).join('、') || '-';
		},
		// 获取住宿状态（从attendees数组中提取）
		getAccommodationStatus(item) {
			if (!item.attendees || !Array.isArray(item.attendees) || item.attendees.length === 0) {
				return '-';
			}
			// 检查是否有参会人需要住宿
			const hasAccommodation = item.attendees.some(a => {
				const acc = a.accommodation;
				if (acc === 1 || acc === '1' || acc === true || acc === 'true' || acc === '是') {
					return true;
				}
				return false;
			});
			return hasAccommodation ? this.t('yes') : this.t('no');
		},
		goToPayment(item) {
			// 跳转到支付页面，传递订单数据
			const orderData = {
				user_participation_id: item.user_participation_id,
				amount_of_participation: item.amount_of_participation,
				conference_name: item.conference_name,
				attendees_data: item.attendees_data,
			};
			
			this.$router.push({
				path: '/user_participation/payment',
				query: {
					orderData: encodeURIComponent(JSON.stringify(orderData))
				}
			});
		},
		viewDetails(item) {
			// 获取当前语言
			const currentLang = this.currentLanguage || 'zh';
			
			// 解析双语文本的辅助函数
			const getBilingualText = (str) => {
				if (!str) return '-';
				try {
					const json = JSON.parse(str);
					if (json && typeof json === 'object' && (json.zh || json.en)) {
						return json[currentLang] || json.zh || json.en || str;
					}
				} catch (e) {
					// 不是 JSON，返回原值
				}
				return str;
			};
			
			// 显示详情信息（使用 Element UI 的 MessageBox）
			const detailsHtml = `
				<div style="text-align: left; padding: 0.5rem 0;">
					<p style="margin: 0.5rem 0;"><strong>${this.t('meetingNumber')}：</strong>${item.meeting_number || '-'}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('meetingNameLabel')}：</strong>${getBilingualText(item.conference_name)}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('meetingTypeLabel')}：</strong>${getBilingualText(item.meeting_type)}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('meetingTimeLabel')}：</strong>${this.formatDateTime(item.meeting_time) || '-'}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('meetingVenueLabel')}：</strong>${getBilingualText(item.meeting_venue)}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('participationAmount')}：</strong>¥${item.amount_of_participation || 0}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('userNameLabel')}：</strong>${this.getAttendeeNames(item) || '-'}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('accommodationRequired')}：</strong>${this.getAccommodationStatus(item) || '-'}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('examineStateLabel')}：</strong>${this.getExamineStateText(item.examine_state || item.examineState)}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('paymentStatusLabel')}：</strong>${this.getPayStateText(item.pay_state || item.payState)}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('paymentMethod')}：</strong>${item.pay_type || '-'}</p>
					<p style="margin: 0.5rem 0;"><strong>${this.t('registrationTime')}：</strong>${this.$toTime(item.create_time, 'yyyy-MM-dd hh:mm:ss')}</p>
					${item.order_notes ? `<p style="margin: 0.5rem 0;"><strong>${this.t('orderNotes')}：</strong>${item.order_notes}</p>` : ''}
				</div>
			`;
			
			this.$alert(detailsHtml, this.t('registrationDetailsTitle'), {
				dangerouslyUseHTMLString: true,
				confirmButtonText: this.t('confirm'),
				type: 'info'
			});
		}
	},
	async mounted() {
		// 页面加载时自动恢复登录状态
		const token = $.db.get("token");
		if (token) {
			// 如果 store 中没有用户信息，尝试从 token 恢复
			const user = this.$store.state.user;
			if (!user || !user.user_id || user.user_id === 0) {
				try {
					console.log('从 token 恢复登录状态...');
					await this.$get_user((user) => {
						console.log('用户信息已恢复:', user);
					});
				} catch (e) {
					console.warn('恢复登录状态失败:', e);
				}
			}
		}
		
		// 加载报名列表
		this.get_list();
	}
};
</script>

<style scoped>
.container {
	min-height: 800px;
}

.participation_header {
	margin-bottom: 2rem;
	padding-bottom: 1rem;
	border-bottom: 2px solid #e8e8e8;
}

.participation_header h3 {
	margin: 0;
	color: #333;
	font-size: 1.5rem;
	font-weight: 600;
}

.participation_header .subtitle {
	margin: 0.5rem 0 0 0;
	color: #666;
	font-size: 0.9rem;
}

.participation_list {
	display: flex;
	flex-direction: column;
	gap: 1.5rem;
}

.participation_item {
	width: 100%;
}

.participation_card {
	background: white;
	border-radius: 8px;
	padding: 1.5rem;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
}

.participation_card:hover {
	box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	transform: translateY(-2px);
}

.card_header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 1rem;
	padding-bottom: 1rem;
	border-bottom: 1px solid #f0f0f0;
}

.conference_name {
	margin: 0;
	font-size: 1.2rem;
	font-weight: 600;
	color: #333;
	flex: 1;
}

.status_badges {
	display: flex;
	gap: 0.5rem;
	flex-shrink: 0;
}

.badge {
	padding: 0.25rem 0.75rem;
	border-radius: 12px;
	font-size: 0.75rem;
	font-weight: 500;
}

.badge_success {
	background: #f0f9ff;
	color: #52c41a;
	border: 1px solid #b7eb8f;
}

.badge_info {
	background: #e6f7ff;
	color: #1890ff;
	border: 1px solid #91d5ff;
}

.badge_warning {
	background: #fff7e6;
	color: #fa8c16;
	border: 1px solid #ffd591;
}

.card_body {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
	gap: 1rem;
	margin-bottom: 1rem;
}

.info_row {
	display: flex;
	flex-wrap: wrap;
	align-items: baseline;
}

.info_label {
	color: #666;
	font-size: 0.9rem;
	margin-right: 0.5rem;
}

.info_value {
	color: #333;
	font-size: 0.95rem;
	font-weight: 500;
}

.info_value.amount {
	color: #ff6600;
	font-size: 1.1rem;
	font-weight: 600;
}

.card_footer {
	display: flex;
	justify-content: flex-end;
	gap: 1rem;
	padding-top: 1rem;
	border-top: 1px solid #f0f0f0;
}

.btn_view,
.btn_pay {
	padding: 0.5rem 1.5rem;
	border-radius: 4px;
	font-size: 0.9rem;
	cursor: pointer;
	transition: all 0.3s ease;
	border: none;
	text-decoration: none;
	display: inline-block;
}

.btn_view {
	background: #f5f5f5;
	color: #333;
}

.btn_view:hover {
	background: #e8e8e8;
}

.btn_pay {
	background: #52c41a;
	color: white;
}

.btn_pay:hover {
	background: #73d13d;
}

.empty_state {
	text-align: center;
	padding: 4rem 2rem;
}

.empty_icon {
	font-size: 4rem;
	margin-bottom: 1rem;
}

.empty_text {
	color: #999;
	font-size: 1rem;
	margin-bottom: 2rem;
}

.btn_primary {
	display: inline-block;
	padding: 0.75rem 2rem;
	background: #52c41a;
	color: white;
	border-radius: 4px;
	text-decoration: none;
	font-size: 1rem;
	transition: all 0.3s ease;
}

.btn_primary:hover {
	background: #73d13d;
}

@media (max-width: 768px) {
	.card_body {
		grid-template-columns: 1fr;
	}

	.card_header {
		flex-direction: column;
		gap: 1rem;
	}

	.status_badges {
		width: 100%;
	}
}
</style>

